import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Tag, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber, 
  message, 
  Tooltip, 
  Popconfirm,
  Alert,
  Divider,
  Typography,
  Progress,
  Badge
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  SettingOutlined,
  BarChartOutlined,
  PieChartOutlined,
  ExperimentOutlined,
  SaveOutlined,
  CalculatorOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Paragraph } = Typography;

const StyleFactorManagement = () => {
  const [styleFactors, setStyleFactors] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingStyle, setEditingStyle] = useState(null);
  const [form] = Form.useForm();

  // 模拟风格投资因子数据
  const mockStyleFactors = [
    {
      id: 1,
      name: '价值风格',
      description: '基于价值投资理念的风格因子，关注低估值、高股息等特征',
      category: '传统风格',
      status: 'active',
      factorCount: 4,
      totalWeight: 1.0,
      factors: [
        { name: '价值因子', weight: 0.4, type: '基本面因子' },
        { name: '股息因子', weight: 0.3, type: '基本面因子' },
        { name: '质量因子', weight: 0.2, type: '基本面因子' },
        { name: '规模因子', weight: 0.1, type: '风险因子' }
      ],
      formula: 'value_style = 0.4*value_factor + 0.3*dividend_factor + 0.2*quality_factor + 0.1*size_factor',
      coverage: 2800,
      lastUpdate: '2024-01-15',
      performance: {
        sharpeRatio: 0.85,
        maxDrawdown: -0.12,
        annualReturn: 0.15
      }
    },
    {
      id: 2,
      name: '成长风格',
      description: '基于成长投资理念的风格因子，关注高增长、高ROE等特征',
      category: '传统风格',
      status: 'active',
      factorCount: 3,
      totalWeight: 1.0,
      factors: [
        { name: '成长因子', weight: 0.5, type: '基本面因子' },
        { name: '质量因子', weight: 0.3, type: '基本面因子' },
        { name: '动量因子', weight: 0.2, type: '技术因子' }
      ],
      formula: 'growth_style = 0.5*growth_factor + 0.3*quality_factor + 0.2*momentum_factor',
      coverage: 2600,
      lastUpdate: '2024-01-15',
      performance: {
        sharpeRatio: 0.92,
        maxDrawdown: -0.18,
        annualReturn: 0.18
      }
    },
    {
      id: 3,
      name: '动量风格',
      description: '基于动量投资理念的风格因子，关注价格趋势和相对强度',
      category: '技术风格',
      status: 'active',
      factorCount: 3,
      totalWeight: 1.0,
      factors: [
        { name: '动量因子', weight: 0.6, type: '技术因子' },
        { name: '流动性因子', weight: 0.25, type: '技术因子' },
        { name: '波动率因子', weight: 0.15, type: '风险因子' }
      ],
      formula: 'momentum_style = 0.6*momentum_factor + 0.25*liquidity_factor + 0.15*volatility_factor',
      coverage: 3200,
      lastUpdate: '2024-01-15',
      performance: {
        sharpeRatio: 0.78,
        maxDrawdown: -0.15,
        annualReturn: 0.12
      }
    },
    {
      id: 4,
      name: '质量风格',
      description: '基于质量投资理念的风格因子，关注盈利质量、财务稳健性',
      category: '传统风格',
      status: 'active',
      factorCount: 4,
      totalWeight: 1.0,
      factors: [
        { name: '质量因子', weight: 0.4, type: '基本面因子' },
        { name: 'ROE因子', weight: 0.3, type: '基本面因子' },
        { name: '债务因子', weight: 0.2, type: '基本面因子' },
        { name: '稳定性因子', weight: 0.1, type: '风险因子' }
      ],
      formula: 'quality_style = 0.4*quality_factor + 0.3*roe_factor + 0.2*debt_factor + 0.1*stability_factor',
      coverage: 2400,
      lastUpdate: '2024-01-10',
      performance: {
        sharpeRatio: 0.95,
        maxDrawdown: -0.08,
        annualReturn: 0.14
      }
    },
    {
      id: 5,
      name: '小盘风格',
      description: '基于小盘股投资理念的风格因子，关注小市值公司的超额收益',
      category: '规模风格',
      status: 'active',
      factorCount: 3,
      totalWeight: 1.0,
      factors: [
        { name: '规模因子', weight: 0.7, type: '风险因子' },
        { name: '流动性因子', weight: 0.2, type: '技术因子' },
        { name: '价值因子', weight: 0.1, type: '基本面因子' }
      ],
      formula: 'small_cap_style = 0.7*size_factor + 0.2*liquidity_factor + 0.1*value_factor',
      coverage: 1800,
      lastUpdate: '2024-01-15',
      performance: {
        sharpeRatio: 0.68,
        maxDrawdown: -0.22,
        annualReturn: 0.16
      }
    },
    {
      id: 6,
      name: 'ESG风格',
      description: '基于ESG投资理念的风格因子，关注环境、社会和治理因素',
      category: '另类风格',
      status: 'active',
      factorCount: 3,
      totalWeight: 1.0,
      factors: [
        { name: 'ESG因子', weight: 0.5, type: '另类因子' },
        { name: '质量因子', weight: 0.3, type: '基本面因子' },
        { name: '风险因子', weight: 0.2, type: '风险因子' }
      ],
      formula: 'esg_style = 0.5*esg_factor + 0.3*quality_factor + 0.2*risk_factor',
      coverage: 1600,
      lastUpdate: '2024-01-10',
      performance: {
        sharpeRatio: 0.82,
        maxDrawdown: -0.10,
        annualReturn: 0.13
      }
    }
  ];

  // 风格分类选项
  const styleCategories = ['传统风格', '技术风格', '规模风格', '另类风格', '混合风格'];
  const availableFactors = [
    { name: '价值因子', type: '基本面因子' },
    { name: '成长因子', type: '基本面因子' },
    { name: '质量因子', type: '基本面因子' },
    { name: '动量因子', type: '技术因子' },
    { name: '规模因子', type: '风险因子' },
    { name: '波动率因子', type: '风险因子' },
    { name: '流动性因子', type: '技术因子' },
    { name: '股息因子', type: '基本面因子' },
    { name: 'ROE因子', type: '基本面因子' },
    { name: '债务因子', type: '基本面因子' },
    { name: '稳定性因子', type: '风险因子' },
    { name: 'ESG因子', type: '另类因子' }
  ];

  useEffect(() => {
    const stored = localStorage.getItem('styleFactorsData');
    if (stored) {
      setStyleFactors(JSON.parse(stored));
    } else {
      setStyleFactors(mockStyleFactors);
    }
  }, []);

  const columns = [
    {
      title: '风格名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{name}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.category}</div>
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 250,
      ellipsis: true,
    },
    {
      title: '因子数量',
      dataIndex: 'factorCount',
      key: 'factorCount',
      width: 100,
      render: (count) => <Tag color="blue">{count}</Tag>,
    },
    {
      title: '覆盖基金',
      dataIndex: 'coverage',
      key: 'coverage',
      width: 120,
      render: (coverage) => <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{coverage}</span>,
    },
    {
      title: '夏普比率',
      key: 'sharpeRatio',
      width: 120,
      render: (_, record) => (
        <span style={{ 
          color: record.performance.sharpeRatio > 0.8 ? '#52c41a' : 
                 record.performance.sharpeRatio > 0.6 ? '#faad14' : '#ff4d4f'
        }}>
          {record.performance.sharpeRatio.toFixed(2)}
        </span>
      ),
    },
    {
      title: '年化收益',
      key: 'annualReturn',
      width: 120,
      render: (_, record) => (
        <span style={{ 
          color: record.performance.annualReturn > 0.15 ? '#52c41a' : 
                 record.performance.annualReturn > 0.10 ? '#faad14' : '#ff4d4f'
        }}>
          {(record.performance.annualReturn * 100).toFixed(1)}%
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Badge 
          status={status === 'active' ? 'success' : 'error'} 
          text={status === 'active' ? '启用' : '停用'} 
        />
      ),
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdate',
      key: 'lastUpdate',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="编辑风格">
            <Button 
              type="link" 
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除风格">
            <Popconfirm
              title="确定要删除这个风格因子吗？"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button 
                type="link" 
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingStyle(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingStyle(record);
    form.setFieldsValue({
      name: record.name,
      description: record.description,
      category: record.category,
      factors: record.factors.map(f => ({ name: f.name, weight: f.weight }))
    });
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    setStyleFactors(styleFactors.filter(style => style.id !== id));
    message.success('删除成功');
  };

  const handleViewDetails = (record) => {
    Modal.info({
      title: `${record.name} - 风格因子详情`,
      width: 800,
      content: (
        <div>
          <Row gutter={16}>
            <Col span={12}>
              <Card size="small" title="基本信息">
                <p><strong>风格名称：</strong>{record.name}</p>
                <p><strong>风格分类：</strong>{record.category}</p>
                <p><strong>因子数量：</strong>{record.factorCount}</p>
                <p><strong>覆盖基金：</strong>{record.coverage}</p>
                <p><strong>状态：</strong>{record.status === 'active' ? '启用' : '停用'}</p>
                <p><strong>最后更新：</strong>{record.lastUpdate}</p>
              </Card>
            </Col>
            <Col span={12}>
              <Card size="small" title="绩效指标">
                <p><strong>夏普比率：</strong>{record.performance.sharpeRatio.toFixed(2)}</p>
                <p><strong>最大回撤：</strong>{(record.performance.maxDrawdown * 100).toFixed(1)}%</p>
                <p><strong>年化收益：</strong>{(record.performance.annualReturn * 100).toFixed(1)}%</p>
              </Card>
            </Col>
          </Row>

          <Card size="small" title="风格描述" style={{ marginTop: '16px' }}>
            <p>{record.description}</p>
          </Card>

          <Card size="small" title="组成因子" style={{ marginTop: '16px' }}>
            <Row gutter={16}>
              {record.factors.map((factor, index) => (
                <Col span={8} key={index}>
                  <div style={{ 
                    padding: '12px', 
                    border: '1px solid #d9d9d9', 
                    borderRadius: '4px',
                    marginBottom: '8px'
                  }}>
                    <div style={{ fontWeight: 'bold' }}>{factor.name}</div>
                    <div style={{ color: '#666', fontSize: '12px' }}>{factor.type}</div>
                    <div style={{ color: '#1890ff', fontWeight: 'bold' }}>
                      {(factor.weight * 100).toFixed(0)}%
                    </div>
                  </div>
                </Col>
              ))}
            </Row>
          </Card>

          <Card size="small" title="计算公式" style={{ marginTop: '16px' }}>
            <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', fontSize: '14px' }}>
              {record.formula}
            </pre>
          </Card>
        </div>
      ),
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingStyle) {
        // 编辑模式
        const updatedStyles = styleFactors.map(style => 
          style.id === editingStyle.id ? { ...style, ...values } : style
        );
        setStyleFactors(updatedStyles);
        localStorage.setItem('styleFactorsData', JSON.stringify(updatedStyles));
        message.success('风格因子更新成功');
      } else {
        // 新增模式
        const newStyle = {
          id: Date.now(),
          ...values,
          status: 'active',
          lastUpdate: new Date().toISOString().split('T')[0],
          coverage: Math.floor(Math.random() * 2000) + 1000,
          performance: {
            sharpeRatio: (Math.random() * 0.5) + 0.5,
            maxDrawdown: -(Math.random() * 0.2) - 0.05,
            annualReturn: (Math.random() * 0.15) + 0.08
          }
        };
        const newList = [...styleFactors, newStyle];
        setStyleFactors(newList);
        localStorage.setItem('styleFactorsData', JSON.stringify(newList));
        message.success('风格因子添加成功');
      }
      
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  const getStyleStats = () => {
    const totalStyles = styleFactors.length;
    const activeStyles = styleFactors.filter(s => s.status === 'active').length;
    const avgSharpeRatio = styleFactors.length > 0 ? 
      styleFactors.reduce((sum, s) => sum + s.performance.sharpeRatio, 0) / styleFactors.length : 0;
    const avgReturn = styleFactors.length > 0 ? 
      styleFactors.reduce((sum, s) => sum + s.performance.annualReturn, 0) / styleFactors.length : 0;

    return { totalStyles, activeStyles, avgSharpeRatio, avgReturn };
  };

  const stats = getStyleStats();

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>风格投资因子管理</Title>
      <Paragraph type="secondary">
        通过多因子加权方式创建风格投资因子分类，支持价值、成长、动量、质量等不同投资风格
      </Paragraph>

      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总风格数" 
              value={stats.totalStyles} 
              prefix={<BarChartOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="启用风格" 
              value={stats.activeStyles} 
              prefix={<PieChartOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均夏普比率" 
              value={stats.avgSharpeRatio.toFixed(2)} 
              prefix={<SettingOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均年化收益" 
              value={(stats.avgReturn * 100).toFixed(1)} 
              suffix="%" 
              prefix={<ExperimentOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作栏 */}
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <h4>风格因子列表</h4>
          <p style={{ color: '#666', margin: 0 }}>
            管理不同的投资风格因子，包括价值、成长、动量、质量等风格
          </p>
        </div>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增风格因子
        </Button>
      </div>

      {/* 风格因子列表 */}
      <Table 
        dataSource={styleFactors} 
        columns={columns} 
        rowKey="id"
        pagination={{
          total: styleFactors.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        scroll={{ x: 1500 }}
      />

      {/* 新增/编辑风格因子模态框 */}
      <Modal
        title={editingStyle ? '编辑风格因子' : '新增风格因子'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ category: '传统风格' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="风格名称"
                rules={[{ required: true, message: '请输入风格名称' }]}
              >
                <Input placeholder="请输入风格名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="风格分类"
                rules={[{ required: true, message: '请选择风格分类' }]}
              >
                <Select placeholder="请选择风格分类">
                  {styleCategories.map(category => (
                    <Option key={category} value={category}>{category}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="风格描述"
            rules={[{ required: true, message: '请输入风格描述' }]}
          >
            <TextArea 
              rows={4}
              placeholder="请输入风格因子的详细描述"
            />
          </Form.Item>

          <Alert
            message="因子配置"
            description="请配置组成该风格的因子及其权重。权重总和应为100%。"
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />

          <Form.List name="factors">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Row gutter={16} key={key} style={{ marginBottom: '16px' }}>
                    <Col span={10}>
                      <Form.Item
                        {...restField}
                        name={[name, 'name']}
                        rules={[{ required: true, message: '请选择因子' }]}
                      >
                        <Select placeholder="选择因子">
                          {availableFactors.map(factor => (
                            <Option key={factor.name} value={factor.name}>
                              {factor.name} - {factor.type}
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        {...restField}
                        name={[name, 'weight']}
                        rules={[{ required: true, message: '请输入权重' }]}
                      >
                        <InputNumber
                          min={0}
                          max={1}
                          step={0.01}
                          style={{ width: '100%' }}
                          placeholder="权重"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Button 
                        type="link" 
                        danger 
                        onClick={() => remove(name)}
                      >
                        删除
                      </Button>
                    </Col>
                  </Row>
                ))}
                <Form.Item>
                  <Button 
                    type="dashed" 
                    onClick={() => add()} 
                    block 
                    icon={<PlusOutlined />}
                  >
                    添加因子
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};

export default StyleFactorManagement; 